package com.gcd.skymallorderapi.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gcd.skymallorderapi.dao.OrderMapper;
import com.gcd.skymallorderapi.service.OrderItemFeignService;
import com.gcd.skymallorderapi.service.ProductFeignService;
import com.situ.model.Cart;
import com.situ.model.Order;
import com.situ.model.OrderItem;
import com.situ.model.search.OrderSearchBean;
import com.situ.service.OrderService;
import com.situ.utils.JsonResult;
import com.situ.utils.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * 订单服务实现类
 * 实现订单相关业务逻辑，包括订单创建、查询、状态更新等功能
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {
    // 添加雪花算法ID生成器实例
    private final SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1);
    private OrderMapper orderMapper;
    private OrderItemFeignService orderItemFeignService;
    private ProductFeignService productFeignService;


    @Autowired
    public void setProductFeignService(ProductFeignService productFeignService) {
        this.productFeignService = productFeignService;
    }

    @Autowired
    public void setOrderItemFeign(OrderItemFeignService orderItemFeignService) {
        this.orderItemFeignService = orderItemFeignService;
    }

    @Autowired
    public void setOrderMapper(OrderMapper orderMapper) {
        this.orderMapper = orderMapper;
    }

    /**
     * 查询所有订单
     *
     * @param page       分页参数
     * @param searchBean 订单搜索条件
     * @return 订单分页结果
     */
    @Override
    public Page<Order> findAll(Page<Order> page, OrderSearchBean searchBean) {
        Page<Order> result = orderMapper.findAll(page, searchBean);
        result.getRecords().forEach(this::patchOrderItems);
        return result;
    }

    //根据秒杀编号查询订单信息
    @Override
    public Order findBySeckillNo(String seckillNo) {
        return orderMapper.findBySeckillNoOrder(seckillNo);
    }

    //根据id查询订单信息
    @Override
    public Order findById(Integer id) {
        return orderMapper.findById(id);
    }


    /**
     * 为订单填充订单项详细信息
     * 通过Feign调用订单项服务获取详细信息
     *
     * @param order 需要填充信息的订单对象
     */
    private void patchOrderItems(Order order) {
        ResponseEntity<JsonResult<Page<OrderItem>>> resp = this.orderItemFeignService.findByOrderId(1, 100, order.getId());
        JsonResult<Page<OrderItem>> jsonResult = resp.getBody();
        if (jsonResult != null) {
            Page<OrderItem> data = jsonResult.getData();
            List<OrderItem> orderItems = data.getRecords();
            order.setOrderItems(orderItems);
        }
    }

    /**
     * 修改订单信息
     *
     * @param order 需要修改的订单对象
     * @return 修改后的订单对象
     */
    @Override
    public Order updateOrder(Order order) {
        return null;
    }

    /**
     * 删除订单
     *
     * @param ids 需要删除的订单ID列表
     * @return 删除的订单数量
     */
    @Override
    public Integer deleteOrder(List<Integer> ids) {
        return 0;
    }

    /**
     * 根据用户ID查询订单金额
     *
     * @param userId 用户ID
     * @return 订单分页结果
     */
    @Override
    public Page<Order> findMoneyByUserId(Integer userId) {
        return null;
    }


    /**
     * 创建普通订单的处理流程：
     * <ol>
     *   <li>订单服务调用购物车服务获取购物车信息（如果还没有的话）</li>
     *   <li>订单服务调用订单项服务，传递购物车信息创建订单项</li>
     *   <li>创建完成后，订单服务再调用订单项服务获取刚创建的订单项并填充到订单对象中</li>
     * </ol>
     *
     * @param carts 购物车列表
     * @return 是否创建成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createOrder(List<Cart> carts) {
        // 先创建一个空订单，不包含订单项
        Order order = new Order();
        order.setOrderNo("ORD" + idGenerator.nextId());
        // 空订单总金额先设为0
        order.setTotalAmount(BigDecimal.ZERO);
        order.setPayStatus(0);
        order.setOrderType(0);
        order.setUserId(carts.getFirst().getUserId());
        // 插入空订单
        boolean orderInserted = orderMapper.insert(order) == 1;
        if (!orderInserted) {
            return false;
        }

        // 直接调用订单项服务，传递购物车列表创建订单项
        ResponseEntity<JsonResult<Boolean>> response = orderItemFeignService.createOrderItem(carts);
        if(response == null || response.getBody()==null) {
            throw new RuntimeException("订单项创建失败");
        }
        Boolean orderItemCreated = response.getBody().getData();
        if (orderItemCreated==null || !orderItemCreated) {
            throw new RuntimeException("订单项插入数据库失败");
        }
        ResponseEntity<JsonResult<Page<OrderItem>>> resp = this.orderItemFeignService.findByOrderId(1, 100, order.getId());
        if (resp != null && resp.getBody() != null && resp.getBody().getData() != null) {
            Page<OrderItem> page = resp.getBody().getData();
            List<OrderItem> orderItems = page.getRecords();
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (OrderItem item : orderItems) {
                totalAmount = totalAmount.add(item.getTotalPrice());
            }
            order.setTotalAmount(totalAmount);
            return orderMapper.updateById(order)==1;
        }
        /*if (response != null && response.getBody() != null) {
            Boolean orderItemCreated = response.getBody().getData();
            if (orderItemCreated != null && orderItemCreated) {
                // 订单项创建成功，通过查询订单项来计算总金额
                ResponseEntity<JsonResult<Page<OrderItem>>> resp = this.orderItemFeignService.findByOrderId(1, 100, order.getId());
                if (resp != null && resp.getBody() != null && resp.getBody().getData() != null) {
                    Page<OrderItem> page = resp.getBody().getData();
                    List<OrderItem> orderItems = page.getRecords();
                    BigDecimal totalAmount = BigDecimal.ZERO;
                    for (OrderItem item : orderItems) {
                        totalAmount = totalAmount.add(item.getTotalPrice());
                    }
                    order.setTotalAmount(totalAmount);
                    return orderMapper.updateById(order)==1;
                }
            }
        }*/
        return false;
    }


    //创建秒杀订单
    @Transactional
    @Override
    public Order createSeckillOrder(Order order) {

        order.setOrderNo("ORD"+idGenerator.nextId());
        BigDecimal amount=BigDecimal.ZERO;
        order.setTotalAmount(amount);
        order.setPayStatus(0);
        order.setOrderStatus(0);
        order.setOrderType(1);
        // 插入空订单
        boolean orderInserted = orderMapper.insert(order) == 1;
        if (!orderInserted) {
            return order;
        }
        for (OrderItem orderItem:order.getOrderItems()) {
            orderItem.setTotalPrice(orderItem.getProductPrice().multiply(BigDecimal.valueOf(orderItem.getQuantity())));
            orderItem.setOrderId(order.getId());
            orderItem.setUserId(order.getUserId());
            orderItem.setUserId(order.getUserId());
            orderItem.setOrderType(order.getOrderType());
            //扣减库存
            ResponseEntity<JsonResult<?>> productRes = productFeignService.decrementStock(orderItem.getProductId(), orderItem.getQuantity());
            if(productRes == null || productRes.getBody() == null) {
                throw new RuntimeException("库存服务调用失败");
            }

            String stockSuccess = (String) productRes.getBody().getData();
            if(!Objects.equals(stockSuccess, "扣减成功")) {
                throw new RuntimeException("库存扣减失败，订单创建失败");
            }

            ResponseEntity<JsonResult<Boolean>> response = orderItemFeignService.createSeckillOrderItem(orderItem);
            if (response == null || response.getBody() == null) {
                throw new RuntimeException("订单项创建失败");
            }

            if (response.getBody().isSuccess()) {
                amount = amount.add(orderItem.getProductPrice().multiply(BigDecimal.valueOf(orderItem.getQuantity())));
            }
        }
        order.setTotalAmount(amount);
        orderMapper.updateById(order);
        return order;
    }


    /**
     * 更新订单支付状态
     *
     * @param id 订单ID
     * @return 是否更新成功
     */
    @Override
    public boolean updatePayStatus(Integer id) {
        //模拟订单支付成功与失败
        if (true) {
            return orderMapper.updatePayStatusInt(id) == 1;
        } else {
            return false;
        }
    }

    /**
     * 后台发货，将订单状态改为已发货
     *
     * @param id 订单ID
     * @return 是否更新成功
     */
    @Override
    public boolean updateOrderStatusTo2(Integer id) {
        return orderMapper.updateSendStatusIntTo2(id) == 1;
    }

    /**
     * 前台确认收货，将订单状态改为已完成
     *
     * @param id 订单ID
     * @return 是否更新成功
     */
    @Override
    public boolean updateOrderStatusTo3(Integer id) {
        return false;
    }

    /**
     * 12小时未支付，订单状态改为已取消
     *
     * @param id 订单ID
     * @return 是否更新成功
     */
    @Override
    public boolean updateStatusTo4(Integer id) {
        return orderMapper.updateStatusTo4(id) == 1;

    }

    /**
     * 用户申请退款，将订单状态改为退款待确认
     *
     * @param id 订单ID
     * @return 是否更新成功
     */
    @Override
    public boolean updateStatusTo5(Integer id) {
        return orderMapper.updateStatusTo5(id) == 1;
    }

    /**
     * 退款成功，将订单状态改为退款成功
     *
     * @param id 订单ID
     * @return 是否更新成功
     */
    @Override
    public boolean updateStatusTo6(Integer id) {
        return orderMapper.updateStatusTo6(id) == 1;
    }
}
